import os
from datetime import datetime

import oss2
import time

# oss
ACCESS_KEY_ID = os.getenv("ALI_ACCESS_KEY", "LTAI5tJXK7ghhavDYZ4jc4qJ")
ACCESS_KEY_SECRET = os.getenv("ALI_ACCESS_SECRET", "jcaqr6LqN2kmiZp9YguEVqPT9XizbE")
END_POINT = "%s://%s" % (
    os.getenv("OSS_SCHEMA", "https"),
    os.getenv("OSS_END_POINT", "oss-cn-beijing.aliyuncs.com"),
)
BUCKET_NAME = os.getenv("OSS_BUCKET_NAME", "redhat1808")
BUCKET_ACL_TYPE = os.getenv("BUCKET_ACL_TYPE", "private")
ALIYUN_OSS_CNAME = ""
OSS_CNAME = os.getenv(
    "OSS_CNAME",
)
OSS_EXPIRE_SECONDS = int(os.getenv("OSS_EXPIRE_SECONDS", "60"))
BUCKET_URL = os.getenv("BUCKET_URL", "https://redhat1808.oss-cn-beijing.aliyuncs.com")

ENABLE_OSS = os.getenv("ENABLE_OSS", "y")


class AliyunOssStorage(object):
    def __init__(self):
        self.bucket = oss2.Bucket(
            oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET), END_POINT, BUCKET_NAME
        )

    def save(self, file_path, file):
        return self.bucket.put_object(file_path, file)

    def delete(self, file_path):
        self.bucket.delete_object(file_path)


def file_path(file, type):
    """返回文件上传路径"""
    file_ext = file.split(".")[-1]
    filename = "%s.%s" % (int(time.time() * 1000), file_ext)
    now = datetime.now()
    parent_folder = "flask/%s/%s/%02d/%02d/" % (type, now.year, now.month, now.day)

    return os.path.join(parent_folder, filename)
